package com.nanako.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nanako.common.R;
import com.nanako.dto.SetmealDto;
import com.nanako.entity.Category;
import com.nanako.entity.Setmeal;
import com.nanako.entity.SetmealDish;
import com.nanako.service.CategoryService;
import com.nanako.service.SetmealDishService;
import com.nanako.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @GetMapping("page")
    public R queryPage(Integer page, Integer pageSize, String name) {
        IPage<Setmeal> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        // 条件分页查询套餐数据
        setmealService.page(pageInfo, wrapper);

        // 将分页查询的数据封装到SetmealDto对象
        List<SetmealDto> setmealDtos = pageInfo.getRecords().stream().map(setmeal -> {
            Category category = categoryService.getById(setmeal.getCategoryId());
            SetmealDto setmealDto = new SetmealDto();
            setmealDto.setCategoryName(category.getName());
            LambdaQueryWrapper<SetmealDish> listWrapper = new LambdaQueryWrapper<>();
            listWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
            List<SetmealDish> setmealDishes = setmealDishService.list(listWrapper);
            setmealDto.setSetmealDishes(setmealDishes);
            BeanUtils.copyProperties(setmeal, setmealDto);
            return setmealDto;
        }).toList();
        Map map = new HashMap();
        map.put("total", pageInfo.getTotal());
        map.put("records", setmealDtos);
        return R.success(map);
    }

    @PostMapping
    public R saveSetmeal(@RequestBody SetmealDto setmealDto) {
        redisTemplate.delete(Objects.requireNonNull(redisTemplate.keys("setmeal*")));
        if (setmealService.addSetmeal(setmealDto)) {
            return R.success("保存套餐成功");
        }
        return R.error("保存套餐失败");
    }

    @DeleteMapping
    public R deleteSetmeal(@RequestParam List<Long> ids) {
        redisTemplate.delete(Objects.requireNonNull(redisTemplate.keys("setmeal*")));
        setmealService.removeSetmealByIds(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R updateStatusBatch(@PathVariable int status, @RequestParam List<Long> ids) {
        redisTemplate.delete(Objects.requireNonNull(redisTemplate.keys("setmeal*")));
        LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Setmeal::getStatus, status).in(Setmeal::getId, ids);
        if (setmealService.update(wrapper)) {
            return R.success("操作成功");
        }
        return R.error("操作失败");
    }

    @GetMapping("/{id}")
    public R queryOne(@PathVariable Long id) {
        return R.success(setmealService.queryOne(id));
    }

    @PutMapping
    public R updateSetmeal(@RequestBody SetmealDto setmealDto) {
        redisTemplate.delete(Objects.requireNonNull(redisTemplate.keys("setmeal*")));
        setmealService.updateSetmeal(setmealDto);
        return R.success("修改套餐成功");
    }

    @GetMapping("/list")
    public R<List<Setmeal>> getSetmealList(Long categoryId, Integer status) {
        Object o = redisTemplate.opsForValue().get("setmeal:" + categoryId);
        if (ObjectUtils.isNotEmpty(o)) {
            return R.success((List<Setmeal>) o);
        }
        List<Setmeal> setmeals = setmealService.list(new LambdaQueryWrapper<Setmeal>()
                .eq(Setmeal::getCategoryId, categoryId)
                .eq(Setmeal::getStatus, status));
        redisTemplate.opsForValue().set("setmeal:" + categoryId, setmeals);
        return R.success(setmeals);
    }

}
